package com.example.community.controller;

import com.example.community.entity.Event;
import com.example.community.entity.User;
import com.example.community.event.EventProducer;
import com.example.community.service.LikeService;
import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUtil;
import com.example.community.util.HostHolder;
import com.example.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: huang
 * @Date: 2021/9/26 19:00
 * @Description:
 */
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *
     * @param entityType
     * @param entityId
     * @return 输入某实体类型和某实体id，获取当前登录用户，执行点赞操作，获取该实体的赞的数量，以及当前登录用户对该实体的点赞状态
     */
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        //获取当前用户
        User user = hostHolder.getUser();

        //点赞功能
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        //显示点赞的数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        //显示点赞的状态，返回的是该用户对某实体的点赞状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        //返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        //触发点赞事件
        if (likeStatus == 1) {
            Event event = new Event()
                    .setUserId(hostHolder.getUser().getId())
                    .setTopic(TOPIC_LIKE)
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setData("postId", postId)
                    .setEntityUserId(entityUserId);
            eventProducer.fireEvent(event);

            //只有对帖子进行点赞我们才计算帖子分数
            if (entityType == ENTITY_TYPE_POST) {
                //计算帖子分数
                String redisKey = RedisKeyUtil.getPostScoreKey();
                redisTemplate.opsForSet().add(redisKey, postId);
            }
        }
        return CommunityUtil.getJSONString(0, null, map);

    }

}
